/*
 * ps2.c
 *
 *  Created on: Nov 19, 2021
 *      Author: zz
 */

#include "ps2.h"
#include <stdio.h>

extern SPI_HandleTypeDef hspi1;

static uint8_t ps2_rx[9];

void ps2_init()
{
	HAL_GPIO_WritePin(PS2_CS_GPIO_Port, PS2_CS_Pin, GPIO_PIN_SET);
}

//PS2处理，周期执行
void ps2_proc(void* arg)
{
	uint8_t tx[9] = {0x01, 0x42, 0x00};

	HAL_GPIO_WritePin(PS2_CS_GPIO_Port, PS2_CS_Pin, GPIO_PIN_RESET);
	tim3_delayus(100);

	HAL_StatusTypeDef ret  = 0;
	for(int i=0; i<9; ++i) {
		ret |= HAL_SPI_TransmitReceive(&hspi1, &tx[i], &ps2_rx[i], 1, 100);
		tim3_delayus(10);//250kbps, 不加延时，数据易出错
	}
	HAL_GPIO_WritePin(PS2_CS_GPIO_Port, PS2_CS_Pin, GPIO_PIN_SET);

//	printf("PS2 %x %x %x %x %x %x %x %x %x\r\n", ps2_rx[0],ps2_rx[1],ps2_rx[2],ps2_rx[3],
//			ps2_rx[4],ps2_rx[5],ps2_rx[6],ps2_rx[7],ps2_rx[8]);
}

//PS2获取按键信息
int ps2_get_btn(PS_BTN no)
{
	if(no<0 || no >= PS_BTN_COUNT) {
		return -1;
	}
	if(no<8) {
		return (ps2_rx[3] & (0x01<<no)) == 0x00;
	}
	else {
		return (ps2_rx[4] & (0x01<<(no-8))) == 0x00;
	}
}
int ps2_get_analog(PS_ANALOG_OFFSET no)
{
	if(no<5 || no > 8) {
		return -1;
	}

	return ps2_rx[no];
}

int ps2_get_mode()
{
	uint8_t *buf = ps2_rx;
	if((buf[0]==0xff)&&(buf[1]==0x41)&&(buf[2]==0x5a))
		return 0;

	if((buf[0]==0xff)&&(buf[1]==0x73)&&(buf[2]==0x5a))
		return 1;

	return -1;
}
void ps2_dump()
{
	printf("PS2 MODE:%d========================:\r\n", ps2_get_mode());
	printf("\tUP:%d, DOWN:%d, RIGHT:%d, LEFT:%d, DELTA:%d, CIRCLE:%d, CROSS:%d, SQUARE:%d\r\n",
			ps2_get_btn(PS_UP),ps2_get_btn(PS_DOWN),ps2_get_btn(PS_RIGHT),ps2_get_btn(PS_LEFT),
			ps2_get_btn(PS_DELTA),ps2_get_btn(PS_CIRCLE),ps2_get_btn(PS_CROSS),ps2_get_btn(PS_SQUARE));

	printf("\tSEL:%d, START:%d, L1:%d, L2:%d, L3:%d, R1:%d, R2:%d, R3:%d\r\n",
				ps2_get_btn(PS_SELECT),ps2_get_btn(PS_START),ps2_get_btn(PS_L1),ps2_get_btn(PS_L2),
				ps2_get_btn(PS_L3),ps2_get_btn(PS_R1),ps2_get_btn(PS_R2),ps2_get_btn(PS_R3));

	printf("\tLX:%d, LY:%d, RX:%d, RY:%d\r\n",
			ps2_get_analog(PS_A_LX),ps2_get_analog(PS_A_LY),ps2_get_analog(PS_A_RX),ps2_get_analog(PS_A_RY));
}
